package com.put.mybills.service;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.put.mybills.R;
import com.put.mybills.activities.MainActivity;
import com.put.mybills.adapter.GlobalParams;
import com.put.mybills.model.Bill;
import com.put.mybills.model.Facture;
import android.accounts.Account;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;


public class NotyficationService extends Service  { 

	private static final int NOTIFY_ME_ID=1337;
	private String TAG = "NotyficationService";
	private GlobalParams globalParams;
	
	
	@Override
	public IBinder onBind(Intent intent) {		
		return null;
	}
	
	@Override
    public void onCreate() {
		Log.d(TAG, "Create for notyfication");
        globalParams = new GlobalParams(getBaseContext());   
        super.onCreate();
    }
		
	@Override
	public void onStart(Intent intent, int startId) {
		Log.d(TAG, "Start for notyfication");
		 super.onDestroy();
	}
	
 	@Override
	public int onStartCommand(Intent intent, int flags, int startId) { 		
 		Log.d(TAG, "Loogkin for notyfication");
		 Calendar cal = Calendar.getInstance();
		 List<Facture> factures = serachBills(cal.getTime(),1);		 
		 for (Facture facture : factures) {
			 createNotyication(facture);
		 }

	     return super.onStartCommand(intent, flags, startId);
	
 	}
 	
 	public void createNotyication(Facture facture) {
 		
 		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
 		Boolean pushupCheckbox = sharedPreferences.getBoolean("notyfication_pushup", false); 		 
 		if (pushupCheckbox) {
	 		String title =  getResources().getString(R.string.notyfication_tittle);
			NotificationManager mgr= (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
		    Notification note=new Notification(R.drawable.ic_launcher, title, System.currentTimeMillis());
		 	PendingIntent i=PendingIntent.getActivity(this, 0,new Intent(this, MainActivity.class),0); 
		 	note.setLatestEventInfo(this, title,getResources().getString(R.string.notyfication_bill) + " " + facture.getName(), i);
		    mgr.notify(NOTIFY_ME_ID, note);	  
		    
		    Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(2000);
		    
 		}	   
	    Boolean emailCheckbox = sharedPreferences.getBoolean("notyfication_email", false);
	    Log.d(TAG, "Email checkbox is " +emailCheckbox );	   

	    if (emailCheckbox) {
	    	String login = sharedPreferences.getString("notyfication_email_login", "");
	    	String password = sharedPreferences.getString("notyfication_email_password", "");
	    	
	    	Log.d(TAG, "login = " + login);
	    	Log.d(TAG, "password = " + password);
	    	
	    	if (!login.equals("") && !password.equals("") && login.contains("@")){
	    		sendMail(login, getResources().getString(R.string.notyfication_tittle), getResources().getString(R.string.notyfication_bill) + " " + facture.getName(),login , password);
	    	}	    	
	    }	
 	}
 	
 	
 	public List<Facture> serachBills(Date currentDate, Integer interval) {
 		
 		final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 		List<Facture> machtedBills = new ArrayList<Facture>(); 		
 		List<Facture> factures = GlobalParams.getInstance().facturedatasource.getAllFactures();
 		
 		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);	
 		
 		
 		String Sreminder = sharedPreferences.getString("notyfication_reminder", "0");
 		int reminder = Integer.parseInt(Sreminder);
 		Log.d(TAG,  "Reminder is :" + reminder);
 		
 		
 		for (Facture facture : factures) {
 			
 			
 			List<Bill> bills = GlobalParams.getInstance().billdatasource.getAllBills(facture.getId());
 			
 			Collections.sort(bills);
 			Log.d(TAG,"SIze of bills is : " +  bills.size());
 			
 			if (bills.size()>0) {
 				Bill bill = bills.get(bills.size()-1);
 				Log.d(TAG,"My id is : " +  bill.getId() + " " + bill.getDate());
 				Calendar c = Calendar.getInstance();		
				
				Date billDate = null;
				try {
					billDate = sdf.parse( bill.getDate());
				} catch (ParseException e) {
					e.printStackTrace();
				}
			
				Calendar cal = Calendar.getInstance();  
				cal.setTime(billDate);  
				cal.add(Calendar.DATE, facture.getInterval()); 
				
				Log.d(TAG, "New date is " + sdf.format(cal.getTime()));
				Log.d(TAG, "Current date is " + sdf.format(currentDate.getTime()));
				  
				int diffInDays = (int)( (cal.getTime().getTime() - currentDate.getTime()) / (1000 * 60 * 60 * 24) );

				Log.d(TAG, "Current Date is : " +  currentDate.getTime() + " diffDays is " + diffInDays );
				
				if (diffInDays == reminder){
					int yes = 0;
					for (Bill bill2 : bills) {
						if(bill.getTmpDate().getMonth() == cal.getTime().getMonth()){
							yes = 1;
							break;
						}
					}

					if (yes==0)
						machtedBills.add(facture);
				}				 			
 			}
	
		} 	
 		return machtedBills;
 	}
 	
 	private void sendMail(String email, String subject, String messageBody, String login, String password) {
        Session session = createSessionObject(login , password);

        try {
            Message message = createMessage(email, subject, messageBody, session, login , password);
            new SendMailTask().execute(message);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private Message createMessage(String email, String subject, String messageBody, Session session, String login, String password) throws MessagingException, UnsupportedEncodingException {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(login, getResources().getString(R.string.app_name)));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
        message.setSubject(subject);
        message.setText(messageBody);
        return message;
    }

    private Session createSessionObject(final String login, final String pasword) {
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.port", "587");

        return Session.getInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(login, pasword);
            }
        });
    }

    private class SendMailTask extends AsyncTask<Message, Void, Void> {
       

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
           
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            
        }

        @Override
        protected Void doInBackground(Message... messages) {
            try {
                Transport.send(messages[0]);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    


 	
 	
}
